package cn.ichiva.web.component;

import cn.ichiva.web.common.Bus;
import cn.ichiva.web.common.Topic;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class Favorites implements Initializable {

    Map<String,String> map = new ConcurrentHashMap<String, String>(){{
        put("码云","https://gitee.com/");
        put("开源中国","https://www.oschina.net/");
        put("百度","https://www.baidu.com/");
    }};

    @FXML
    HBox root;

    public Favorites(){
        Bus.subscribe(Topic.Favorite, json -> {
            JSONObject jsonObject = JSON.parseObject(json);
            String title = jsonObject.getString("title");
            String url = jsonObject.getString("url");
            add(title,url);
        });
    }

    public void add(String title,String url){
        root.getChildren().add(new FavoritesButton(title,url));
    }

    public void remove(String url){

    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        List<FavoritesButton> collect = map.entrySet().stream().map(e -> new FavoritesButton(e.getKey(), e.getValue())).collect(Collectors.toList());
        root.getChildren().addAll(collect);
    }

    class FavoritesButton extends Button{
        public FavoritesButton(String text,String url){
            setText(text);
            setOnMouseClicked(event -> Bus.publish(Topic.TurnTo,url));
        }
    }

}
